package com.pdd.controller;

import com.pdd.beans.Product;
import com.pdd.dto.DTO;
import com.pdd.service.ProductService;
import com.pdd.util.UploadUtil;
import com.pdd.vo.product.ProductAddVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;

/**
 * @创建时间: 2018/8/21 - 15:14
 * @编写人员: 丷教皇
 * @文件描述:
 */
@Controller
@CrossOrigin(origins = { "*" })
@Api(description = "商品接口")
public class ProductController {

    @Autowired
    @Setter
    private ProductService productService;

    @ApiOperation(value = "添加商品信息")
    @RequestMapping(value = "/product",method = RequestMethod.POST)
    @ResponseBody
    public DTO add(MultipartFile logo, ProductAddVO vo, HttpServletRequest request){

        //执行上传
        String targetName = UploadUtil.upload(logo,request);

        //1. 封装参数
        Product product = new Product();
        product.setP_cid(vo.getP_cid());
        product.setP_title(vo.getP_title());
        product.setP_desc(vo.getP_desc());
        product.setP_price_old(vo.getP_price_old());
        product.setP_price_new(vo.getP_price_new());
        product.setP_count(vo.getP_count());
        product.setP_detail(vo.getP_detail());
        product.setP_order(vo.getP_order());
        product.setP_status(vo.isP_status());

        //2. 执行新增
        boolean result = productService.addProduct(product);

        //3. 创建DTO,并返回
        if(result){
            return DTO.success();
        }else{
            return DTO.error();
        }
    }

    @ApiOperation(value = "获得所有商品信息")
    @RequestMapping(value = "/product",method = RequestMethod.GET)
    @ResponseBody
    public DTO get(){

        //1. 执行查询操作
        List<Product> list = productService.getAll();

        System.out.println(list);

        //2. 封装DTO
        DTO dto = new DTO(list);
        //3. 返回结果
        return dto;
    }

    @ApiOperation(value = "按分类查询商品信息")
    @RequestMapping(value = "/product/{p_cid}",method = RequestMethod.GET)
    @ResponseBody
    public DTO getByPcId(@ApiParam(value = "分类编号") @PathVariable(name = "p_cid") Integer p_cid){

        //1.执行查询操作
        List<Product> list = productService.getByPcId(p_cid);

        //2.封装DTo
        DTO dto = new DTO(list);

        //3.返回结果
        return dto;
    }

}
